package com.symbio.ishenapi.order.controller;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.symbio.ishenapi.common.bean.LoginUser;
import com.symbio.ishenapi.common.controller.BaseController;
import com.symbio.ishenapi.order.ExcelExport.ExcelExportUtil;
import com.symbio.ishenapi.order.bean.DoctorFousParam;
import com.symbio.ishenapi.order.bean.TmDoctorUser;
import com.symbio.ishenapi.order.model.*;
import com.symbio.ishenapi.order.tencent.WxParamsMaker;
import com.symbio.ishenapi.order.util.postUtil;
import io.jboot.web.controller.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("/TmServicesOrderController")
public class TmServicesOrderController extends BaseController {


    /**
     *
     * 生成支付订单接口
     *
     */
    public void saveTmServicesOrder(){      //添加服务订单
        String userId =getPara("userId");//患者id
        String userSex =getPara("userSex");//患者性别
        String userAge =getPara("userAge");//患者年龄
        String userName =getPara("userName");//患者名称
        String userTEL =getPara("userTEL");//患者手机号
        String doctorId =getPara("doctorId");//医生id
        String doctorName =getPara("doctorName");//医生名称
        String doctorTitle =getPara("doctorTitle");//医生职务
        String doctorGender =getPara("doctorGender");//医生性别
        String doctorTEL = getPara("doctorTEL");//医生电话
        String orderType =getPara("orderType");//订单类型
        String orderPrice =getPara("orderPrice");//订单价格
        String userHeadPortrait = getPara("userHeadPortrait");//医生头像
        String userPortrait = getPara("userPortrait");//患者头像
        String orderSource = getPara("orderSource");

        if(userHeadPortrait == null && "".equals(userHeadPortrait)){//判断医生头像是否为空
            userHeadPortrait = "";
        }
        if(userPortrait == null && "".equals(userPortrait)){//判断患者头像是否为空
            userPortrait = "";
        }
        if(doctorTitle == null && "".equals(doctorTitle)){//判断医生职务
            doctorTitle = "";
        }


        if (userId == null || "".equals(userId)) {
            renderJsonError(40003, "患者编号");
        }else if (doctorId == null || "".equals(doctorId)){
            renderJsonError(40003, "医生编号");
        }else if (orderType == null || "".equals(orderType)){
            renderJsonError(40003, "订单类型");
        }else if (orderPrice == null || "".equals(orderPrice)){
            renderJsonError(40003, "订单价格");
        }else{
            TmServiceOrder user = new TmServiceOrder();
            user.setUserId(new BigInteger(userId));
            user.setUserName(userName);
            user.setUserTEL(userTEL);
            if(userAge != null && !"".equals(userAge)){
                user.setUserAge(Integer.parseInt(userAge));
            }else{
                user.setUserAge(0);
                userAge = "0";
            }

            user.setUserSex(userSex);
            user.setDoctorId(new BigInteger(doctorId));
            user.setDoctorName(doctorName);
            user.setDoctorTEL(doctorTEL);
            user.setOrderType(orderType);
            user.setOrderPrice(Double.parseDouble(orderPrice));
            user.setCreateTime(new Date());
            user.setStatus("1");
            user.setOrderStatus("18918001");
            user.setOrderSource(orderSource);
            user.setOrderCode(WxParamsMaker.orderNoMaker());//生成订单编号
            System.out.println("订单类型====="+user.getOrderType());
            System.out.println("订单来源====="+user.getOrderSource());

            boolean b= user.save();
            if(b){
                TmRegister register = new TmRegister();
                register.setOrderId(user.getId());
                register.setDoctorId(new BigInteger(doctorId));
                register.setDoctorName(doctorName);
                register.setDoctorAvatar(userHeadPortrait);
                register.setDoctorGender(Long.parseLong(doctorGender));
                register.setDoctorTitle(doctorTitle);
                register.setPatientId(user.getUserId());
                register.setPatientName(userName);
                register.setPatientAge(userAge);
                register.setPatientGender(Long.parseLong(userAge));
                register.setPatientAvatar(userPortrait);
                register.setUserType(2L);
                register.setStatus(1L);
                register.setCreateTime(new Date());
                register.save();
              /*  TmOrderDictionary tod = TmOrderDictionary.dao.getOrderServiceTypeByOrderSource(user.getOrderType(),user.getOrderSource());
                System.out.println("获取字典表的状态======"+tod);
                if(tod != null){
                    if (!"180919005".equals(user.getOrderSource())) {
                        String param = "{\n" +
                                "\"doctor_id\":" + user.getDoctorId() + ", \n" +
                                "\"doctor_nickname\":\"" + user.getDoctorName() + "\",\n" +
                                "\"doctor_avatar\":\"" + userHeadPortrait + "\", \n" +
                                "\"doctor_gender\":" + doctorGender + ", \n" +
                                "\"doctor_title\":\"" + doctorTitle + "\", \n" +
                                "\"patient_id\":" + user.getUserId() + ", \n" +
                                "\"patient_nickname\":\"" + user.getUserName() + "\", \n" +
                                "\"patient_avatar\":\"" + userPortrait + "\", \n" +
                                "\"patient_gender\":" + userSex + ",\n" +
                                "\"patient_age\":\"" + userAge + "\", \n" +
                                // "\"assistant_id\":3, \n" +
                                //"\"assistant_avatar\":\"http://ishen-data.oss-cn-beijing.aliyuncs.com/picture/1543284941712.png\", \n" +
                                "\"user_type\":2, \n" +
                                "\"room_type\":" + tod.getStatus() + " \n" +
                                "}";
                        System.out.println("注册请求报文=====" + param);
                        String str = postUtil.sendPost("https://talkzilla.dev.sibosen.com/api/v1/user/register", param);
                        System.out.println(str);

                    }
                }*/
                String str = "";
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("str", str);
                map.put("id", user.getId());
                renderJson(map);
            }else{
                renderJsonError(40003,"订单");
                return;
            }
        }
    }

    public void findTmServicesOrder(){      //显示
        long id = getParaToLong("id");
        TmServiceOrder item = TmServiceOrder.dao.findById(id);
        if (item == null ) {
            renderJsonError(40003);
            return;
        }
        renderJsonRet(item);
    }

    public void register(){
        String doctorId = getPara("doctorId");
        String doctorName = getPara("doctorName");
        String doctorGender = getPara("doctorGender");
        String doctorTitle = getPara("doctorTitle");
        String userId = getPara("userId");
        String userName = getPara("userName");
        String userSex = getPara("userSex");
        String userAge = getPara("userAge");
        String param ="{\n" +
                "\"doctor_id\":"+doctorId+", \n" +
                "\"doctor_nickname\":\""+doctorName+"\",\n" +
                //"\"doctor_avatar\":\"http://ishen-data.oss-cn-beijing.aliyuncs.com/picture/1543284941712.png\", \n" +
                "\"doctor_gender\":"+doctorGender+", \n" +
                "\"doctor_title\":\""+doctorTitle+"\", \n" +
                "\"patient_id\":"+userId+", \n" +
                "\"patient_nickname\":\""+userName+"\", \n" +
                //"\"patient_avatar\":\"http://ishen-data.oss-cn-beijing.aliyuncs.com/picture/1543284941712.png\", \n" +
                "\"patient_gender\":"+userSex+",\n" +
                "\"patient_age\":\""+userAge+"\", \n" +
                // "\"assistant_id\":3, \n" +
                //"\"assistant_avatar\":\"http://ishen-data.oss-cn-beijing.aliyuncs.com/picture/1543284941712.png\", \n" +
                "\"user_type\":2, \n" +
                "\"roomType\":1 \n" +
                "}";
        String str = postUtil.sendPost("https://talkzilla.dev.sibosen.com/api/v1/user/register",param);
        System.out.println(str);
        renderJsonRet(str);
        return;
    }

    /*
     * 查询最新订单列表  时间查询
     * */
    public void selectPhoto(){
        TmServiceOrder ts =(TmServiceOrder)getReqBodyObject(TmServiceOrder.class);
        List<Record> list = TmServiceOrder.dao.selectNewOredr(ts);
        if (list == null ) {
            renderJsonError(40003);
            return;
        }
        renderJsonRet(list);
    }

    /**
     * 修改订单删除状态，单条
     */
    public void updTmServicesOrder(){       //删除
    TmServiceOrder user = (TmServiceOrder) getReqBodyObject(TmServiceOrder.class);
    System.out.println(user);
        TmServiceOrder u = TmServiceOrder.dao.findById(user.getId());
        if (u!=null) {
            u.setStatus("0");
            if (u.update()) {
                renderJsonError(40001,"订单删除");
            } else {
                renderJsonError(40005);
            }
        }else{
            renderJsonError(40003);
            return;
        }
    }

    public void likeServiceOrder(){  //查找订单 username
        TmServiceOrder user = (TmServiceOrder) getReqBodyObject(TmServiceOrder.class);
        TmServiceOrder user1 = new TmServiceOrder();
        user1.setUserName(user.getUserName());
        List<Record> list=TmServiceOrder.dao.likeOrder(user1);
        renderJsonRet(list);
    }

    public void findServiceOrder(){         //查询订单
        TmServiceOrder user = (TmServiceOrder)getReqBodyObject(TmServiceOrder.class);
        List<Record> list = TmServiceOrder.dao.selectServiceOrder(user);
        renderJsonRet(list);
     }

    /*
     * 修改
     * */
    public void photoUpdateOrder() {
        TmServiceOrder ts = (TmServiceOrder) getReqBodyObject(TmServiceOrder.class);
        TmServiceOrder byId = TmServiceOrder.dao.findById(ts.getId());
        System.out.print("1111111111111111111111"+byId.getId()+"aaaaaaaa");
        if (byId != null) {
            if (!StrKit.isBlank(ts.getId().toString())) byId.setId(ts.getId());
            if (!StrKit.isBlank(ts.getUserId().toString())) byId.setUserId(ts.getUserId());
            if (!StrKit.isBlank(ts.getOrderPrice().toString())) byId.setOrderPrice(ts.getOrderPrice());
            if (!StrKit.isBlank(ts.getOrderPayType())) byId.setOrderPayType(ts.getOrderPayType());
            if (!StrKit.isBlank(ts.getOrderType())) byId.setOrderType(ts.getOrderType());
            if (!StrKit.isBlank(ts.getOrderCode())) byId.setOrderCode(ts.getOrderCode());
            if (!StrKit.isBlank(ts.getOrderStatus())) byId.setOrderStatus(ts.getOrderStatus());
            if (!StrKit.isBlank(ts.getUserName())) byId.setUserName(ts.getUserName());
            if (!StrKit.isBlank(ts.getUserAge().toString())) byId.setUserAge(ts.getUserAge());
            if (!StrKit.isBlank(ts.getDoctorName())) byId.setDoctorName(ts.getDoctorName());
            if (!StrKit.isBlank(ts.getDoctorId().toString())) byId.setDoctorId(ts.getDoctorId());
            if (!StrKit.isBlank(ts.getStatus())) byId.setStatus(ts.getStatus());
            byId.setCreateTime(new Date());
            if (byId.update()) {
                renderJsonRet(ts.getId());
            } else {
                renderJsonError(40005);
            }
        }else{
            System.out.println("数据库中用户信息为空");
            renderJsonError(40003);
            return;
        }
    }

    /**
     * @Author GuoShunYou
     * @Description 通过订单id查询订单详情
     * @date 下午 2:39   2018/10/22
     * @return void
     */
    public void getOrderByid(){
        TmServiceOrder ts = (TmServiceOrder) getReqBodyObject(TmServiceOrder.class);
        if(ts.getId()==null || "".equals(ts.getId())){
            renderJsonError(40003, "订单id");
            return;
        }
        Record tm=TmServiceOrder.dao.findOne2(ts);
        if(tm==null){
            List lsit=new ArrayList<>();
            renderJsonRet(lsit);
            return;
        }
        renderJsonRet(tm);
    }



    /**
     *
     *
     * @Author GuoShunYou
     * @Description 通过多个订单id查询对应的userId
     * @date 下午 8:19   2018/11/10
     * @return void
     */
    public void selectIdbyListIid(){
        TmServiceOrder ts = (TmServiceOrder) getReqBodyObject(TmServiceOrder.class);
        String userid=TmServiceOrder.dao.selectUserId(ts.getOrderType());
        if(userid==null){
            renderJsonError(40003, "该订单对应患者");
        }else{
            renderJsonRet(userid);
        }

    }


    /**
     * @Author GuoShunYou
     * @Description 通过userid、订单状态查询订单
     * @date 下午 8:16   2018/10/21 0021
     * @return void
     */
    public void selectAll(){
        TmServiceOrder ts = (TmServiceOrder) getReqBodyObject(TmServiceOrder.class);
        if(ts.getUserId()==null || "".equals(ts.getUserId())){
            renderJsonError(40003, "userId");
            return;
        }
        List<Record> list=TmServiceOrder.dao.selectAll(ts);
        renderJsonRet(list);
    }
    /**
     * @Author GuoShunYou
     * @Description 更改订单状态为  预约中  并且添加预约时间,并且把预约次数表的次数减一
     * @date 下午 5:26   2018/10/22
     * @return void
     */
    public void updateOrderById(){
        //TmServiceOrder ts = (TmServiceOrder) getReqBodyObject(TmServiceOrder.class);
        String id = getPara("id");//订单id
        String subscribeDate = getPara("subscribeDate");//预约时间
        String timeSlot = getPara("timeSlot");//预约时间段
       if(id == null || "".equals(id)){
           renderJsonError(40003,"订单编号");
           return;
       }
        if(subscribeDate == null || "".equals(subscribeDate)){
            renderJsonError(40003,"预约时间");
            return;
        }
        if(timeSlot == null || "".equals(timeSlot)){
            renderJsonError(40003,"预约时间段");
            return;
        }
        TmServiceOrder ts = new TmServiceOrder();
        ts.setId(new BigInteger(id));
        TmServiceOrder tso=TmServiceOrder.dao.findOne(ts);//查询订单

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = formatter.parse(subscribeDate);
        }catch (Exception e){
            e.printStackTrace();
        }
        TmSubscribeRecord tmSubscribeRecord = TmSubscribeRecord.dao.getBySubscribeRecord(new BigInteger(id),date,timeSlot);//查询预约记录
        if(tmSubscribeRecord == null){//判断预约记录里是否存在，不存在直接存否则先删除在村
            TmJournal tmJournal = new TmJournal();//保存删除操作日志
            tmJournal.setCreateTime(new Date());
            tmJournal.setDescribe("删除了一条数据");
            tmJournal.setOrderId(tso.getId());
            tmJournal.setStatus(0L);
            tmJournal.setOperatorName("管理员");
            tmJournal.save();

            TmSubscribeRecord tsr = new TmSubscribeRecord();//保存
            tsr.setOrderId(tso.getId());
            tsr.setCreateTime(new Date());
            tsr.setAppointmentDate(date);
            tsr.setTimeSlot(timeSlot);
            tsr.save();
            //保存新增操作日志
            TmJournal tj = new TmJournal();
            tj.setCreateTime(new Date());
            tj.setDescribe("保存了一条数据");
            tj.setOrderId(tso.getId());
            tj.setStatus(0L);
            tj.setOperatorName("管理员");
            tj.save();
        }else{
            if(tmSubscribeRecord.delete()){//删除预约记录
                TmJournal tmJournal = new TmJournal();//保存删除操作日志
                tmJournal.setCreateTime(new Date());
                tmJournal.setDescribe("删除了一条数据");
                tmJournal.setOrderId(tso.getId());
                tmJournal.setStatus(0L);
                tmJournal.setOperatorName("管理员");
                tmJournal.save();

                TmSubscribeRecord tsr = new TmSubscribeRecord();//保存
                tsr.setOrderId(tso.getId());
                tsr.setCreateTime(new Date());
                tsr.setAppointmentDate(date);
                tsr.setTimeSlot(timeSlot);
                tsr.save();
                //保存新增操作日志
                TmJournal tj = new TmJournal();
                tj.setCreateTime(new Date());
                tj.setDescribe("保存了一条数据");
                tj.setOrderId(tso.getId());
                tj.setStatus(0L);
                tj.setOperatorName("管理员");
                tj.save();
            }
        }

        tso.setSubscribeDate(subscribeDate);
        tso.setOrderStatus("18918004");
        boolean b=tso.update();
        if(b){
            renderJson(40001);
        }else{
            renderJsonError(50002,"预约时间");
        }
    }

    public void getOrderPriceById(){
        TmServiceOrder ts = (TmServiceOrder) getReqBodyObject(TmServiceOrder.class);
    }

    /**
     * 后台订单列表分页查询
     * param invoiceStatus ---是否开发票 0.不开 1.开
     */
    public void findBackList(){
        String orderStatus = getPara("orderStatus");
        String orderType = getPara("orderType");
        String orderFlag = getPara("orderFlag");
        Map map = TmServiceOrder.dao.findList(getQueryModel(),orderStatus,orderType,orderFlag);
        renderPageJsonRet(map.get("count"),map.get("data"));
    }

    /**
     * 后台订单列表分页查询
     */
    public void findUserOrder(){
        String userId = getPara("id");
        Map map = TmServiceOrder.dao.findUserOrder(getQueryModel(),userId);
        renderPageJsonRet(map.get("count"),map.get("data"));
    }

    /**
     * 飞
     * wy: 查询全部订单
     */
    public void findOrderAll(){
        TmServiceOrder t = new TmServiceOrder();
        String orderId = getPara("id");
        BigInteger id = null;
        if(orderId != null && !"".equals(orderId)){
            id = new BigInteger(orderId);
        }
        String doctorId = getPara("doctorId");//医生id
        String userName = getPara("userName");//患者名称
        String userTEL = getPara("userTEL");//患者手机号
        String doctorName = getPara("doctorName");//医生名称
        String doctorTEL = getPara("doctorTEL");//医生手机号
        String orderType = getPara("orderType");//订单类型
        String orderStatus = getPara("orderStatus");//订单状态
        String orderServiceType = getPara("orderServiceType");//套餐类型
        Date beginTime = getParaToDate("beginTime");//下单开始时间
        Date endTime = getParaToDate("endTime");//下单结束时间
        Date subscribeDateBegin = getParaToDate("subscribeDateBegin");//预约开始时间
        Date subscribeDateEnd = getParaToDate("subscribeDateEnd");//预约结束时间
        String assistantName = getPara("assistantName");

        LoginUser loginUser = getLoginUser();
        String Ids = "";
        if(loginUser == null){
            Ids = loginUser.getDoctorIds();
            if (Ids.endsWith(",")) {
                Ids = Ids.substring(0,(Ids.length() - 1));
            }
        }


        //封装到对象里
        t.setId(id);
        if(doctorId != null && !"".equals(doctorId)){
            t.setDoctorId(new BigInteger(doctorId));
        }else{
            t.setDoctorId(null);
        }

        t.setUserName(userName);
        t.setUserTEL(userTEL);
        t.setDoctorName(doctorName);
        t.setDoctorTEL(doctorTEL);
        t.setOrderStatus(orderStatus);
        t.setOrderType(orderType);
        t.setOrderServiceType(orderServiceType);
        t.setAssistantName(assistantName);


        Map map = TmServiceOrder.dao.findOrderAll(t, beginTime, endTime,subscribeDateBegin,subscribeDateEnd,getQueryModel(),Ids);
        if (null != map && map.size() > 0){
            renderPageJsonRet(map.get("count"),map.get("data"));
        }else {
            renderJsonError(40003,"请重试!");
        }
    }


    /**
     * 飞
     * 查询待处理订单
     *
     */
    public void findHandleOrder(){
        TmServiceOrder t = new TmServiceOrder();
        String orderId = getPara("id");
        BigInteger id = null;
        if(orderId != null && !"".equals(orderId)){
            id = new BigInteger(orderId);
        }
        String userName = getPara("userName");//患者名称
        String userTEL = getPara("userTEL");//患者手机号
        String doctorName = getPara("doctorName");//医生名称
        String doctorTEL = getPara("doctorTEL");//医生手机号
        String orderType = getPara("orderType");//订单类型
        String orderStatus = getPara("orderStatus");//订单状态
        String orderServiceType = getPara("orderServiceType");//套餐类型
        Date beginTime = getParaToDate("beginTime");//下单开始时间
        Date endTime = getParaToDate("endTime");//下单结束时间
        Date subscribeDateBegin = getParaToDate("subscribeDateBegin");//预约开始时间
        Date subscribeDateEnd = getParaToDate("subscribeDateEnd");//预约结束时间
        String assistantName = getPara("assistantName");

        //封装到对象里
        t.setId(id);
        t.setUserName(userName);
        t.setUserTEL(userTEL);
        t.setDoctorName(doctorName);
        t.setDoctorTEL(doctorTEL);
        t.setOrderStatus(orderStatus);
        t.setOrderType(orderType);
        t.setOrderServiceType(orderServiceType);
        t.setAssistantName(assistantName);

        Map map = TmServiceOrder.dao.findHandleOrder(t, beginTime, endTime,subscribeDateBegin,subscribeDateEnd,getQueryModel());
        if (null != map && map.size() > 0){
            renderPageJsonRet(map.get("count"),map.get("data"));
        }else {
            renderJsonError(40003,"请重试!");
        }
    }


    /**
     * 飞
     * 查询今日新订单
     */
    public void findNewOrder(){
        TmServiceOrder t = new TmServiceOrder();
        String orderId = getPara("id");
        BigInteger id = null;
        if(orderId != null && !"".equals(orderId)){
            id = new BigInteger(orderId);
        }
        String userName = getPara("userName");//患者名称
        String userTEL = getPara("userTEL");//患者手机号
        String doctorName = getPara("doctorName");//医生名称
        String doctorTEL = getPara("doctorTEL");//医生手机号
        String orderType = getPara("orderType");//订单类型
        String orderStatus = getPara("orderStatus");//订单状态
        String orderServiceType = getPara("orderServiceType");//套餐类型
        Date beginTime = getParaToDate("beginTime");//下单开始时间
        Date endTime = getParaToDate("endTime");//下单结束时间
        Date subscribeDateBegin = getParaToDate("subscribeDateBegin");//预约开始时间
        Date subscribeDateEnd = getParaToDate("subscribeDateEnd");//预约结束时间
        String assistantName = getPara("assistantName");

        //封装到对象里
        t.setId(id);
        t.setUserName(userName);
        t.setUserTEL(userTEL);
        t.setDoctorName(doctorName);
        t.setDoctorTEL(doctorTEL);
        t.setOrderStatus(orderStatus);
        t.setOrderType(orderType);
        t.setOrderServiceType(orderServiceType);
        t.setAssistantName(assistantName);

        Map map = TmServiceOrder.dao.findNewOrder(t, beginTime, endTime,subscribeDateBegin,subscribeDateEnd,getQueryModel());
        if (null != map && map.size() > 0){
            renderPageJsonRet(map.get("count"),map.get("data"));
        }else {
            renderJsonError(40003,"请重试!");
        }
    }


    /**
     * @Author jianghy
     * @Description 根据医生id和订单的状态查看各种服务的次数
     * @date 下午 5:26   2018/11/3
     * @return void
     */
    public void queryDoctorFwInfo(){
        String doctorId = getPara("doctorId");//需要查询的医生Id
        String wcStandCode = getPara("wcStandCode");//已完成状态的编码
        String twServiceType = getPara("twServiceType");//图片咨询编码
        String dhServiceType = getPara("dhServiceType");//电话咨询编码
        String spServiceType = getPara("spServiceType");//视频咨询编码
        String kyServiceType = getPara("kyServiceType");//快速开药编码
        Map zzmap = new HashMap();
        Map map = TmOrderCount.dao.queryFgCountAndPatientCount(doctorId);
        Map mapq = TmServiceOrder.dao.queryDoctorFwCount(doctorId,wcStandCode,twServiceType,dhServiceType,spServiceType,kyServiceType);
        zzmap.put("patientCount",map.get("patientCount"));
        zzmap.put("fgPatientCount",map.get("fgPatientCount"));
        zzmap.put("focusCount",map.get("focusCount"));
        zzmap.put("graphicCount",mapq.get("graphicCount"));
        zzmap.put("phoneCount",mapq.get("phoneCount"));
        zzmap.put("videoCount",mapq.get("videoCount"));
        zzmap.put("drugCount",mapq.get("drugCount"));
        zzmap.put("numCount",mapq.get("numCount"));
        renderJsonRet(zzmap);
    }

    /**
     * 飞
     * 修改订单删除状态，批量
     */
    public void updateListOrder(){       //删除
        String idse = getReqBodyString().replace("\"","").replace("\"","");
        List<TmServiceOrder> tmServiceOrderList = TmServiceOrder.dao.findByIdList(idse);
        for(TmServiceOrder tmServiceOrder : tmServiceOrderList){
            tmServiceOrder.setStatus("0");
            if (tmServiceOrder.update()){
                renderJsonRet(40001);
            }else {
                renderError(40002);
            }
        }
    }

    /**
     *飞
     * 导出订单，Excel
     */
    public void exportOrder(){
        HttpServletResponse response = getResponse();
        TmServiceOrder t = new TmServiceOrder();
        String orderId = getPara("id");
        BigInteger id = null;
        if(orderId != null && !"".equals(orderId)){
            id = new BigInteger(orderId);
        }
        String userName = getPara("userName");//患者名称
        String userTEL = getPara("userTEL");//患者手机号
        String doctorName = getPara("doctorName");//医生名称
        String doctorTEL = getPara("doctorTEL");//医生手机号
        String orderType = getPara("orderType");//订单类型
        String orderStatus = getPara("orderStatus");//订单状态
        String orderServiceType = getPara("orderServiceType");//套餐类型
        Date beginTime = getParaToDate("beginTime");//下单开始时间
        Date endTime = getParaToDate("endTime");//下单结束时间
        Date subscribeDateBegin = getParaToDate("subscribeDateBegin");//预约开始时间
        Date subscribeDateEnd = getParaToDate("subscribeDateEnd");//预约结束时间
        String assistantName = getPara("assistantName");//医助名称

        //封装到对象里
        t.setUserName(userName);
        t.setUserTEL(userTEL);
        t.setDoctorName(doctorName);
        t.setDoctorTEL(doctorTEL);
        t.setOrderStatus(orderStatus);
        t.setOrderType(orderType);
        t.setOrderServiceType(orderServiceType);
        t.setAssistantName(assistantName);


        List<TmServiceOrder> list = TmServiceOrder.dao.exportOrder(t, beginTime, endTime,subscribeDateBegin,subscribeDateEnd);

        String sheetName = "订单表单";
        String titleName = "订单表单";
        String fileName = "订单表单";
        int columnNumber = 11;
        int[] columnWidth = { 10, 20, 10,20,10,20,20,10,20,20,10 };
        /*String[][] dataList = { { "001", "2015-01-01", "IT" },
                { "002", "2015-01-02", "市场部" }, { "003", "2015-01-03", "测试" } };*/
        String[] columnName = { "就诊流水号", "订单状态", "患者名称","患者手机号","医生名称","医生手机号","订单类型","套餐类型","下单时间","预约时间","医助" };
        ExcelExportUtil expor = new ExcelExportUtil();
        String str = "";

        try {
            str = expor.ExportNoResponse(sheetName, titleName, fileName,
                    columnNumber, columnWidth, columnName, list,response);
            renderJsonError(40003,str);
            return;
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("这出错");
        }
    }

    /**
     * 根据订单id获取订单信息，飞
     */
    public void getById(){
        TmServiceOrder tso = (TmServiceOrder) getReqBodyObject(TmServiceOrder.class);
        if(tso.getId() == null){
            renderJsonError(40003,"订单编号");
        }else{
            TmServiceOrder tmServiceOrder = TmServiceOrder.dao.getById(tso.getId());
            renderJsonRet(tmServiceOrder);
        }
    }

    /**
     * @Author jianghy
     * @Description 平台数据-订单数（图文订单180919001  、电话订单180919002  、视频订单180919003  、开药订单 180919004 ）
     *              （总订单  180919001，180919002，180919003，180919004）
     * @date
     * @return void
     */
    public void  statisticalGraphicOrderNum(){
        //格式转换
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //接收的统计开始时间
        String startTime = getPara("startTime");
        //接收的统计结束时间
        String endTime = getPara("endTime");
        //输入查询业务的类型的 Code（图文、电话、视频、开药、订单总数）
        String serviceTypeCode = getPara("serviceTypeCode");
        //订单状态Code
        String orderStatus = getPara("orderStatus");
        //当前时间
        Date n = new Date();
        //当前时间的近一个月时间
        Calendar c = Calendar.getInstance();
        c.setTime(n);
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
        //初始化时间为空
        if(startTime==null||"".equals(startTime))
            //现在的时间 格式yyyy-MM-dd
            startTime = format.format(m);
        if(endTime==null||"".equals(endTime))
            //近一个月的时间 格式yyyy-MM-dd
            endTime = format.format(n);
        //计算时间差
        int daysBetween = 0;
        Date d1= new Date();
        Date d2= new Date();
        try{
            d1=format.parse(startTime);
            d2=format.parse(endTime);
            //两个时间相差的天数
            daysBetween = new Long((d2.getTime()-d1.getTime())/(60*60*24*1000)).intValue()+1;
        }catch (Exception e){
            e.printStackTrace();
        }
        String[] finishTimes = new String[daysBetween];
        String[] counts = new String[daysBetween];
        Map map = new LinkedHashMap();
        if(("".equals(serviceTypeCode)||serviceTypeCode==null)||("".equals(orderStatus)||orderStatus==null)){
            renderJsonError(50002,"查询");
        }else {//如果业务类型初始化不为空的时候
            Integer sumCounts = 0;//某种业务某个时间段的订单的累计
            for(int i=0;i<daysBetween;i++) {
                Date date = new Date();
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(d1);
                calendar.add(Calendar.DATE, i);
                date = calendar.getTime();
                String time = format.format(date);
                Record record = TmServiceOrder.dao.queryServiceCountByTime(serviceTypeCode,orderStatus,time);
                finishTimes[i] = time;
                counts[i] = Long.toString(record.get("count"));
                sumCounts+= Integer.valueOf(counts[i]);
            }
            map.put("finishTimes",finishTimes);
            map.put("counts",counts);
            map.put("sumCounts",sumCounts);
            renderJsonRet(map);
        }
    }


    /**
     * 根据订单类型查询总数量，飞
     * 2018-11-17
     */
    public void countOrder(){
        TmServiceOrder tso = (TmServiceOrder)getReqBodyObject(TmServiceOrder.class);
        int number = TmServiceOrder.dao.countOrder(tso);
        renderJsonRet(number);
    }


    /**
     * 飞
     * wy: 通过医生id和患者id获取患者订单
     */
    public void getdoctorBypatient(){
        TmServiceOrder t = new TmServiceOrder();

        String doctorId = getPara("doctorId");//医生id
        String userId = getPara("userId");//患者名称
        String orderStatus = getPara("orderStatus");//订单状态


        //封装到对象里

        if(doctorId != null && !"".equals(doctorId)){
            t.setDoctorId(new BigInteger(doctorId));
        }else{
            t.setDoctorId(null);
        }

        t.setDoctorId(new BigInteger(doctorId));
        t.setUserId(new BigInteger(userId));
        t.setOrderStatus(orderStatus);


        Map map = TmServiceOrder.dao.getDoctorBypatient(t,getQueryModel());
        if (null != map && map.size() > 0){
            renderPageJsonRet(map.get("count"),map.get("data"));
        }else {
            renderJsonError(40003,"请重试!");
        }
    }



    public void updateIsStatus(){
        TmServiceOrder tmServiceOrder = (TmServiceOrder)getReqBodyObject(TmServiceOrder.class);
        TmServiceOrder tso = TmServiceOrder.dao.findById(tmServiceOrder.getId());
        if(tso != null){
            tso.setIsStatus(0);
            if(tso.update()){
               renderJson(40021);
            }
        }else{
            renderJsonError(40004,"订单");
        }
    }

    /**
     * @Author jianghy
     * @Description 复购患者数（平台维度）
     * @date
     * @return void
     */
    public void queryRepeatPurchasePt(){
        Map map = new LinkedHashMap();
        //格式转换
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //接收的统计开始时间
        String startTime = getPara("startTime");
        //接收的统计结束时间
        String endTime = getPara("endTime");
        //输入查询业务的类型（查询图文、电话、视频、开药4种订单）的Code 180919001,180919002,180919003,180919004
        String serviceTypeCode = getPara("serviceTypeCode");
        //订单状态Code
        String orderStatus = getPara("orderStatus");//18918002
        //当前时间
        Date n = new Date();
        //当前时间的近一个月时间
        Calendar c = Calendar.getInstance();
        c.setTime(n);
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
        //初始化时间为空
        if(startTime==null||"".equals(startTime))
            //现在的时间 格式yyyy-MM-dd
            startTime = format.format(m);
        if(endTime==null||"".equals(endTime))
            //近一个月的时间 格式yyyy-MM-dd
            endTime = format.format(n);
        //计算时间差
        int daysBetween = 0;
        Date d1= new Date();
        Date d2= new Date();
        try{
            d1=format.parse(startTime);
            d2=format.parse(endTime);
            //两个时间相差的天数
            daysBetween = new Long((d2.getTime()-d1.getTime())/(60*60*24*1000)).intValue()+1;
        }catch (Exception e){
            e.printStackTrace();
        }
        String[] newCounts = new String[daysBetween];
        String[] finishTimes = new String[daysBetween];
        String[] fgCounts = new String[daysBetween];
        if((serviceTypeCode!=null||!"".equals(serviceTypeCode))||(orderStatus!=null||!"".equals(orderStatus))){
            for(int i=0;i<daysBetween;i++) {
                int newcount = 0;//新增患者数计数
                int fgcount = 0;//新增复购患者数计数
                Date date = new Date();
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(d1);
                calendar.add(Calendar.DATE, i);
                date = calendar.getTime();
                String time = format.format(date);
                List<Record> list = TmServiceOrder.dao.queryPatientCountNum(serviceTypeCode,orderStatus,time);
                finishTimes[i] = time;
                for(int j =0;j<list.size();j++){
                    if(Integer.valueOf(list.get(j).get("count").toString())>1){
                        fgcount++;
                    }else if(Integer.valueOf(list.get(j).get("count").toString())==1){
                        int count = TmServiceOrder.dao.queryFgPatientCountNum(serviceTypeCode,orderStatus,time,list.get(j).get("userId").toString());
                        if(count>1){
                            fgcount++;
                        }else{
                            newcount++;
                        }
                    }
                }
                fgCounts[i] = String.valueOf(fgcount);
                newCounts[i] = String.valueOf(newcount);
            }
            map.put("finishTimes",finishTimes);
            map.put("newCounts",newCounts);
            map.put("fgCounts",fgCounts);
            renderJsonRet(map);
        }else{
            renderJsonError(50002,"查询");
        }
    }
    /**
     * @Author jianghy
     * @Description 复购患者数（医生维度）
     * @date
     * @return void
     */
    public void queryRepeatPurchaseYs(){
        Map map = new LinkedHashMap();
        TmDoctorUser tdu = (TmDoctorUser)getReqBodyObject(TmDoctorUser.class);
        if(tdu !=null){
            List<TmDoctorUser> tduList = tdu.getData();
            String[] doctorName = new String[tduList.size()];//医生名字
            String[] doctorId = new String[tduList.size()];//医生id
            for(int i=0;i<tduList.size();i++){
                doctorName[i] = tduList.get(i).getUserName();
                doctorId[i] = String.valueOf(tduList.get(i).getId());
            }
            map.put("doctorName",doctorName);
            //格式转换
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            //接收的统计开始时间
            String startTime = tdu.getStartTime();
            //接收的统计结束时间
            String endTime = tdu.getEndTime();
            //输入查询业务的类型（查询图文、电话、视频、开药4种订单）的Code 180919001，180919002，180919003，180919004
            String serviceTypeCode = tdu.getServiceTypeCode();
            //订单状态Code
            String orderStatus = tdu.getOrderStatus();//18918002
            //当前时间
            Date n = new Date();
            //当前时间的近一个月时间
            Calendar c = Calendar.getInstance();
            c.setTime(n);
            c.add(Calendar.MONTH, -1);
            Date m = c.getTime();
            //初始化时间为空
            if(startTime==null||"".equals(startTime))
                //现在的时间 格式yyyy-MM-dd
                startTime = format.format(m);
            if(endTime==null||"".equals(endTime))
                //近一个月的时间 格式yyyy-MM-dd
                endTime = format.format(n);
            int fgCount = 0;//根据医生id记录医生的复购患者数
            String[] fgCounts = new String[doctorId.length];
            for(int i =0;i<doctorId.length;i++){
                List<Record> list = TmServiceOrder.dao.queryYsFgPatientCountNum(serviceTypeCode,orderStatus,startTime,endTime,doctorId[i]);
                for(int j=0;j<list.size();j++){
                    if(Integer.parseInt(list.get(j).get("count").toString())>=2){
                        fgCount++;
                    }
                }
                fgCounts[i] = String.valueOf(fgCount);
            }
            map.put("fgCounts",fgCounts);
            renderJsonRet(map);
        }else{
            renderJsonError(50002,"医生复购患者数查看");
        }

    }

    /**
     *
     *
     * @Author GuoShunYou
     * @Description 修改订单状态
     * @date 上午 10:58   2018/11/23
     * @return void
     */
    public void updateOrderStatus(){
        TmServiceOrder tmServiceOrder = (TmServiceOrder)getReqBodyObject(TmServiceOrder.class);
        if(tmServiceOrder.update()){
            renderJsonError(40004,"订单状态");
        }else{
            renderJsonError(40005,"订单状态");
        }
    }
    /**
     * @Author jianghy
     * @Description 平台数据-医生维度关注患者数，根据医生id查询名下已购买服务的患者个数
     * @date
     * @return void
     */
    public void queryHaveToBuyPatient(){
        Map map = new LinkedHashMap();
        //格式转换
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        DoctorFousParam dfp = (DoctorFousParam)getReqBodyObject(DoctorFousParam.class);
        if(dfp!=null){
            String[] doctorName = dfp.getDoctorName();
            String[] doctorIds = dfp.getDoctorIds();
            String[] counts = dfp.getCounts();
            String[] haveToBuyCounts = new String[doctorIds.length];
            map.put("doctorName",doctorName);
            map.put("counts",counts);
            String startTime = dfp.getStartTime();
            String endTime = dfp.getEndTime();
            //当前时间
            Date n = new Date();
            //当前时间的近一个月时间
            Calendar c = Calendar.getInstance();
            c.setTime(n);
            c.add(Calendar.MONTH, -1);
            Date m = c.getTime();
            //初始化时间为空
            if(startTime==null||"".equals(startTime))
                //现在的时间 格式yyyy-MM-dd
                startTime = format.format(m);
            if(endTime==null||"".equals(endTime))
                //近一个月的时间 格式yyyy-MM-dd
                endTime = format.format(n);
            String orderStatus = dfp.getOrderStatus();
            String serviceTypeCode = dfp.getServiceTypeCode();
            for(int i=0;i<doctorIds.length;i++){
                int count = TmServiceOrder.dao.queryHaveToBuyPatient(serviceTypeCode,orderStatus,startTime,endTime,doctorIds[i]);
                haveToBuyCounts[i] = String.valueOf(count);
            }
            map.put("haveToBuyCounts",haveToBuyCounts);
            renderJsonRet(map);
        }else{
            renderJsonError(50002);
        }
    }





    /**
     *
     * 修改订单支付状态和支付记录表的支付状态
     *
     *
     */
    public void updateStatus(){
        String orderId = getPara("orderId");//订单id
        String orderStatus = getPara("orderStatus");//订单状态
        String prepay_id = getPara("prepay_id");//微信支付id
        TmServiceOrder tmServiceOrder = TmServiceOrder.dao.getById(new BigInteger(orderId));
        tmServiceOrder.setOrderStatus(orderStatus);
        if(tmServiceOrder.update()){
            TmPaymentRecord record = TmPaymentRecord.dao.findByPrepayId(prepay_id);
            if(record != null)
                record.setPayResult(orderStatus);
            record.update();
            if ("182010003".equals(tmServiceOrder.getOrderSource())) {
                TmOrderDictionary tod = TmOrderDictionary.dao.getOrderServiceTypeByOrderSource(tmServiceOrder.getOrderType(),tmServiceOrder.getOrderSource());
                TmRegister register = TmRegister.dao.getFind(new BigInteger(orderId));
                System.out.println("获取字典表的状态======"+tod);
                if(register != null){
                    if(tod != null){

                        String param = "{\n" +
                                "\"doctor_id\":" + register.getDoctorId() + ", \n" +
                                "\"doctor_nickname\":\"" + register.getDoctorName() + "\",\n" +
                                "\"doctor_avatar\":\"" + register.getDoctorAvatar() + "\", \n" +
                                "\"doctor_gender\":" + register.getDoctorGender() + ", \n" +
                                "\"doctor_title\":\"" + register.getDoctorTitle() + "\", \n" +
                                "\"patient_id\":" + register.getPatientId() + ", \n" +
                                "\"patient_nickname\":\"" + register.getPatientName()+ "\", \n" +
                                "\"patient_avatar\":\"" + register.getPatientAvatar() + "\", \n" +
                                "\"patient_gender\":" + register.getPatientGender() + ",\n" +
                                "\"patient_age\":\"" + register.getPatientAge() + "\", \n" +
                                // "\"assistant_id\":3, \n" +
                                //"\"assistant_avatar\":\"http://ishen-data.oss-cn-beijing.aliyuncs.com/picture/1543284941712.png\", \n" +
                                "\"user_type\":2, \n" +
                                "\"room_type\":" + tod.getStatus() + " \n" +
                                "}";
                        System.out.println("注册请求报文=====" + param);
                        String str = postUtil.sendPost("https://talkzilla.dev.sibosen.com/api/v1/user/register", param);
                        System.out.println(str);

                    }
                }
            }



            renderJsonError(40004,"订单状态");
        }else{
            renderJsonError(40005,"订单状态");
        }
    }


    /**
     *
     * 生成已支付订单接口
     *
     *
     */
    public void saveServicesOrder(){
        String userId =getPara("userId");//患者id
        String userSex =getPara("userSex");//患者性别
        String userAge =getPara("userAge");//患者年龄
        String userName =getPara("userName");//患者名称
        String userTEL =getPara("userTEL");//患者手机号
        String doctorId =getPara("doctorId");//医生id
        String doctorName =getPara("doctorName");//医生名称
        String doctorTitle =getPara("doctorTitle");//医生职务
        String doctorGender =getPara("doctorGender");//医生性别
        String doctorTEL = getPara("doctorTEL");//医生电话
        String orderType =getPara("orderType");//订单类型
        String orderPrice =getPara("orderPrice");//订单价格
        String userHeadPortrait = getPara("userHeadPortrait");//医生头像
        String userPortrait = getPara("userPortrait");//患者头像
        String orderSource = getPara("orderSource");

        if(userHeadPortrait == null && "".equals(userHeadPortrait)){//判断医生头像是否为空
            userHeadPortrait = "";
        }
        if(userPortrait == null && "".equals(userPortrait)){//判断患者头像是否为空
            userPortrait = "";
        }
        if(doctorTitle == null && "".equals(doctorTitle)){//判断医生职务
            doctorTitle = "";
        }


        if (userId == null || "".equals(userId)) {
            renderJsonError(40003, "患者编号");
        }else if (doctorId == null || "".equals(doctorId)){
            renderJsonError(40003, "医生编号");
        }else if (orderType == null || "".equals(orderType)){
            renderJsonError(40003, "订单类型");
        }else if (orderPrice == null || "".equals(orderPrice)){
            renderJsonError(40003, "订单价格");
        }else{
            TmServiceOrder user = new TmServiceOrder();
            user.setUserId(new BigInteger(userId));
            user.setUserName(userName);
            user.setUserTEL(userTEL);
            if(userAge != null && !"".equals(userAge)){
                user.setUserAge(Integer.parseInt(userAge));
            }else{
                user.setUserAge(0);
                userAge = "0";
            }

            user.setUserSex(userSex);
            user.setDoctorId(new BigInteger(doctorId));
            user.setDoctorName(doctorName);
            user.setDoctorTEL(doctorTEL);
            user.setOrderType(orderType);
            user.setOrderPrice(Double.parseDouble(orderPrice));
            user.setCreateTime(new Date());
            user.setStatus("1");
            user.setOrderStatus("18918005");
            user.setOrderSource(orderSource);
            user.setOrderCode(WxParamsMaker.orderNoMaker());//生成订单编号
            System.out.println("订单类型====="+user.getOrderType());
            System.out.println("订单来源====="+user.getOrderSource());

            boolean b= user.save();
            if(b){
                TmRegister register = new TmRegister();
                register.setOrderId(user.getId());
                register.setDoctorId(new BigInteger(doctorId));
                register.setDoctorName(doctorName);
                register.setDoctorAvatar(userHeadPortrait);
                register.setDoctorGender(Long.parseLong(doctorGender));
                register.setDoctorTitle(doctorTitle);
                register.setPatientId(user.getUserId());
                register.setPatientName(userName);
                register.setPatientAge(userAge);
                register.setPatientGender(Long.parseLong(userAge));
                register.setPatientAvatar(userPortrait);
                register.setUserType(2L);
                register.setStatus(1L);
                register.setCreateTime(new Date());
                register.save();
                TmOrderDictionary tod = TmOrderDictionary.dao.getOrderServiceTypeByOrderSource(user.getOrderType(),user.getOrderSource());
                System.out.println("获取字典表的状态======"+tod);
                if(tod != null){
                    if (!"182010003".equals(user.getOrderSource())) {//注册IM
                        String param = "{\n" +
                                "\"doctor_id\":" + user.getDoctorId() + ", \n" +
                                "\"doctor_nickname\":\"" + user.getDoctorName() + "\",\n" +
                                "\"doctor_avatar\":\"" + userHeadPortrait + "\", \n" +
                                "\"doctor_gender\":" + doctorGender + ", \n" +
                                "\"doctor_title\":\"" + doctorTitle + "\", \n" +
                                "\"patient_id\":" + user.getUserId() + ", \n" +
                                "\"patient_nickname\":\"" + user.getUserName() + "\", \n" +
                                "\"patient_avatar\":\"" + userPortrait + "\", \n" +
                                "\"patient_gender\":" + userSex + ",\n" +
                                "\"patient_age\":\"" + userAge + "\", \n" +
                                // "\"assistant_id\":3, \n" +
                                //"\"assistant_avatar\":\"http://ishen-data.oss-cn-beijing.aliyuncs.com/picture/1543284941712.png\", \n" +
                                "\"user_type\":2, \n" +
                                "\"room_type\":" + tod.getStatus() + " \n" +
                                "}";
                        System.out.println("注册请求报文=====" + param);
                        String str = postUtil.sendPost("https://talkzilla.dev.sibosen.com/api/v1/user/register", param);
                        System.out.println(str);
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("str", str);
                        map.put("id", user.getId());
                        renderJson(map);
                    }
                }
            }else{
                renderJsonError(40003,"订单");
                return;
            }
        }
    }



    /**
     * @Author jianghy
     * @Description 查询app订单详情中的订单信息
     * @date 2018-12-14 17:24
     * @return Record
     */
    public void queryOrderOneInfo(){
        String orderId = getPara("orderId");//订单id
        if(orderId==null||"".equals(orderId)){
            renderJsonError(50002);
            return;
        }
        Record tm=TmServiceOrder.dao.findOneOrder(orderId);
        if(tm==null){
            List list=new ArrayList<>();
            renderJsonRet(list);
            return;
        }
        renderJsonRet(tm);
    }

}

